package patrol.mobile.com.mobilepatrol.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import patrol.mobile.com.mobilepatrol.R;

/**
 * Created by apple on 17/10/16.
 */

public class AddSubView extends RelativeLayout implements View.OnClickListener, TextWatcher {
    private int fen = 1; //
    TextView tv_sub;
    TextView tv_add;
    EditText et_fen;
    private OnFenChangeListener mListener;
    private TextView tv;

    public AddSubView(Context context) {
        super(context,null);
    }

    public AddSubView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.item_add_sub, this);
        tv = ((TextView) findViewById(R.id.tv));
        et_fen = (EditText) findViewById(R.id.et_fen);
        tv_add = (TextView) findViewById(R.id.tv_add);
        tv_sub = (TextView) findViewById(R.id.tv_sub);
        tv_add.setOnClickListener(this);
        tv_sub.setOnClickListener(this);
        et_fen.addTextChangedListener(this);

    }

    public AddSubView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    public void setTv(String str) {
        this.tv.setText(str);
    }

    public void setFen(int fen) {
        this.et_fen.setText(fen+"");
    }
    public int getFen() {
        return Integer.valueOf(et_fen.getText().toString().trim());
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.toString().isEmpty())
            return;
        fen = Integer.valueOf(s.toString());

        if (mListener != null) {
            mListener.onFenChange(this, fen);
        }
    }
    public void setOnFenChangeListener(OnFenChangeListener onAmountChangeListener) {
        this.mListener = onAmountChangeListener;
    }
    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_sub) {
            if (fen > 1) {
                fen--;
                et_fen.setText(fen + "");
            }
        } else if (i == R.id.tv_add) {
            if (fen<10){
                fen++;
                et_fen.setText(fen + "");
            }

        }

        et_fen.clearFocus();

        if (mListener != null) {
            mListener.onFenChange(this, fen);
        }
    }
    public interface OnFenChangeListener {
        void onFenChange(View view, int amount);
    }
}
